# WPF Main Window - Workflow Manager
# 编码: UTF-8

# 加载必要的程序集
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase
Add-Type -AssemblyName System.Windows.Forms

# 设置控制台编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

# 加载 XAML
$xamlPath = Join-Path $PSScriptRoot "MainWindow.xaml"
[xml]$xaml = Get-Content $xamlPath -Encoding UTF8

$reader = New-Object System.Xml.XmlNodeReader $xaml
$window = [Windows.Markup.XamlReader]::Load($reader)

# 获取控件引用
$txtSearchWorkflows = $window.FindName("txtSearchWorkflows")
$txtSearchPlaceholder = $window.FindName("txtSearchPlaceholder")
$treeWorkflows = $window.FindName("treeWorkflows")
$btnNewWorkflow = $window.FindName("btnNewWorkflow")
$btnRefresh = $window.FindName("btnRefresh")
$txtDetailTitle = $window.FindName("txtDetailTitle")
$btnEdit = $window.FindName("btnEdit")
$btnDelete = $window.FindName("btnDelete")
$tabDetails = $window.FindName("tabDetails")
$panelOverview = $window.FindName("panelOverview")
$panelRequirements = $window.FindName("panelRequirements")
$panelTasks = $window.FindName("panelTasks")
$panelDeliverables = $window.FindName("panelDeliverables")
$txtSearchTasks = $window.FindName("txtSearchTasks")
$txtSearchTasksPlaceholder = $window.FindName("txtSearchTasksPlaceholder")

# ============================================
# 占位符文本处理
# ============================================
function Setup-PlaceholderText {
    param($textBox, $placeholder)
    
    # GotFocus - 隐藏占位符
    $textBox.Add_GotFocus({
        $placeholder.Visibility = [Windows.Visibility]::Collapsed
    })
    
    # LostFocus - 如果为空则显示占位符
    $textBox.Add_LostFocus({
        if ([string]::IsNullOrWhiteSpace($textBox.Text)) {
            $placeholder.Visibility = [Windows.Visibility]::Visible
        }
    })
    
    # TextChanged - 有文本时隐藏占位符
    $textBox.Add_TextChanged({
        if ([string]::IsNullOrWhiteSpace($textBox.Text)) {
            $placeholder.Visibility = [Windows.Visibility]::Visible
        } else {
            $placeholder.Visibility = [Windows.Visibility]::Collapsed
        }
    })
}

Setup-PlaceholderText -textBox $txtSearchWorkflows -placeholder $txtSearchPlaceholder
Setup-PlaceholderText -textBox $txtSearchTasks -placeholder $txtSearchTasksPlaceholder

# ============================================
# 数据加载函数
# ============================================
function Load-Workflows {
    try {
        $response = Invoke-RestMethod -Uri "http://localhost:9081/api/workflows" -Method Get -ContentType "application/json; charset=utf-8"
        
        $treeWorkflows.Items.Clear()
        
        if ($response.workflows -and $response.workflows.Count -gt 0) {
            foreach ($workflow in $response.workflows) {
                $item = New-Object System.Windows.Controls.TreeViewItem
                $item.Header = $workflow.name
                $item.Tag = $workflow
                
                # Add child nodes (projects)
                if ($workflow.projects -and $workflow.projects.Count -gt 0) {
                    foreach ($project in $workflow.projects) {
                        $projectItem = New-Object System.Windows.Controls.TreeViewItem
                        $projectItem.Header = "Project: $($project.name)"
                        $projectItem.Tag = $project
                        $item.Items.Add($projectItem)
                    }
                }
                
                $treeWorkflows.Items.Add($item)
            }
        } else {
            $emptyItem = New-Object System.Windows.Controls.TreeViewItem
            $emptyItem.Header = "No workflows"
            $emptyItem.IsEnabled = $false
            $treeWorkflows.Items.Add($emptyItem)
        }
    }
    catch {
        [System.Windows.MessageBox]::Show("Failed to load workflows: $($_.Exception.Message)", "Error", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Error)
    }
}

# ============================================
# 显示详情函数
# ============================================
function Show-WorkflowDetails {
    param($workflow)
    
    $txtDetailTitle.Text = $workflow.name
    $btnEdit.Visibility = [Windows.Visibility]::Visible
    $btnDelete.Visibility = [Windows.Visibility]::Visible
    
    # 清空面板
    $panelOverview.Children.Clear()
    $panelRequirements.Children.Clear()
    $panelTasks.Children.Clear()
    $panelDeliverables.Children.Clear()
    
    # Overview
    $overviewText = New-Object System.Windows.Controls.TextBlock
    $overviewText.Text = @"
Name: $($workflow.name)
Description: $($workflow.description)
Created: $($workflow.created_at)
Status: $($workflow.status)
"@
    $overviewText.FontSize = 14
    $overviewText.TextWrapping = [Windows.TextWrapping]::Wrap
    $panelOverview.Children.Add($overviewText)
    
    # Requirements
    if ($workflow.requirements -and $workflow.requirements.Count -gt 0) {
        foreach ($req in $workflow.requirements) {
            $reqBlock = New-Object System.Windows.Controls.TextBlock
            $reqBlock.Text = "- $($req.description)"
            $reqBlock.FontSize = 14
            $reqBlock.Margin = "0,0,0,8"
            $reqBlock.TextWrapping = [Windows.TextWrapping]::Wrap
            $panelRequirements.Children.Add($reqBlock)
        }
    }
    
    # Tasks
    if ($workflow.tasks -and $workflow.tasks.Count -gt 0) {
        foreach ($task in $workflow.tasks) {
            $taskBlock = New-Object System.Windows.Controls.TextBlock
            $taskBlock.Text = "[$($task.status)] $($task.name)"
            $taskBlock.FontSize = 14
            $taskBlock.Margin = "0,0,0,8"
            $taskBlock.TextWrapping = [Windows.TextWrapping]::Wrap
            $panelTasks.Children.Add($taskBlock)
        }
    }
    
    # Deliverables
    if ($workflow.deliverables -and $workflow.deliverables.Count -gt 0) {
        foreach ($deliverable in $workflow.deliverables) {
            $delBlock = New-Object System.Windows.Controls.TextBlock
            $delBlock.Text = "- $($deliverable.name)"
            $delBlock.FontSize = 14
            $delBlock.Margin = "0,0,0,8"
            $delBlock.TextWrapping = [Windows.TextWrapping]::Wrap
            $panelDeliverables.Children.Add($delBlock)
        }
    }
}

# ============================================
# 事件处理
# ============================================

# TreeView 选择变化
$treeWorkflows.Add_SelectedItemChanged({
    $selectedItem = $treeWorkflows.SelectedItem
    if ($selectedItem -and $selectedItem.Tag) {
        Show-WorkflowDetails -workflow $selectedItem.Tag
    }
})

# 搜索工作流
$txtSearchWorkflows.Add_TextChanged({
    $searchText = $txtSearchWorkflows.Text.ToLower()
    
    foreach ($item in $treeWorkflows.Items) {
        if ([string]::IsNullOrWhiteSpace($searchText)) {
            $item.Visibility = [Windows.Visibility]::Visible
        } else {
            $header = $item.Header.ToString().ToLower()
            if ($header.Contains($searchText)) {
                $item.Visibility = [Windows.Visibility]::Visible
            } else {
                $item.Visibility = [Windows.Visibility]::Collapsed
            }
        }
    }
})

# 搜索任务
$txtSearchTasks.Add_TextChanged({
    $searchText = $txtSearchTasks.Text.ToLower()
    
    foreach ($child in $panelTasks.Children) {
        if ([string]::IsNullOrWhiteSpace($searchText)) {
            $child.Visibility = [Windows.Visibility]::Visible
        } else {
            $text = $child.Text.ToLower()
            if ($text.Contains($searchText)) {
                $child.Visibility = [Windows.Visibility]::Visible
            } else {
                $child.Visibility = [Windows.Visibility]::Collapsed
            }
        }
    }
})

# New workflow button
$btnNewWorkflow.Add_Click({
    try {
        # Call create workflow PowerShell script
        $createFormPath = Join-Path (Split-Path $PSScriptRoot) "create_workflow_form.ps1"
        $result = & powershell.exe -ExecutionPolicy Bypass -File $createFormPath
        
        if ($result) {
            Load-Workflows
            [System.Windows.MessageBox]::Show("Workflow created successfully!", "Success", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Information)
        }
    }
    catch {
        [System.Windows.MessageBox]::Show("Failed to create workflow: $($_.Exception.Message)", "Error", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Error)
    }
})

# Refresh button
$btnRefresh.Add_Click({
    Load-Workflows
})

# Edit button
$btnEdit.Add_Click({
    [System.Windows.MessageBox]::Show("Edit feature coming soon", "Info", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Information)
})

# Delete button
$btnDelete.Add_Click({
    $result = [System.Windows.MessageBox]::Show("Are you sure you want to delete this workflow?", "Confirm Delete", [System.Windows.MessageBoxButton]::YesNo, [System.Windows.MessageBoxImage]::Warning)
    
    if ($result -eq [System.Windows.MessageBoxResult]::Yes) {
        [System.Windows.MessageBox]::Show("Delete feature coming soon", "Info", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Information)
    }
})

# ============================================
# 初始化
# ============================================
Load-Workflows

# 显示窗口
$window.ShowDialog() | Out-Null
